﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using FluxJpeg.Core;
//using FluxJpeg.Core.Crop;
using FluxJpeg.Core.Decoder;
using FluxJpeg.Core.Encoder;
//using FluxJpeg.Core.Filter;
//using FluxJpeg.Core.Resize;
using FluxJpeg.Core.Filtering;
using FluxImage = FluxJpeg.Core.Image;

namespace SUMO.MediaBrowser.Foundation
{
    public static class LibraryHelper
    {

   


        public static byte[] CreateCroppedImage(byte[] buffer, RectangleGeometry cropArea)
        {
            return ManipulateImage(buffer, 0, cropArea);
        }

        public static byte[] CreateResizedImage(byte[] buffer, double scaleModifier)
        {
            return ManipulateImage(buffer, scaleModifier, null);
        }

        public static ImageSource CreateImageSource(string url)
        {
            Uri uri = new Uri(url, UriKind.Absolute);
            return new BitmapImage(uri);
        }

        public static Stream ConvertBufferToStream(byte[] buffer)
        {
            return new MemoryStream(buffer);
        }

        public static byte[] ConvertStreamToBuffer(Stream stream)
        {
            return new BinaryReader(stream).ReadBytes((int) stream.Length);
        }

        public static string RetrieveFilename(string url)
        {
            const string pattern = @"/(([A-Z]|[a-z]|[0-9])+\.jpg)$";
            Regex regex = new Regex(pattern);
            Match match = regex.Match(url);
            if (match.Success)
            {
                return match.Groups[1].Value;
            }

            return String.Empty;
        }

      
        private static byte[] ManipulateImage(byte[] buffer, double scaleModifier, RectangleGeometry cropArea)
        {
    //        DecodedJpeg jpegOut;
    //        // Decode
    //        DecodedJpeg jpegIn = new JpegDecoder(ConvertBufferToStream(buffer)).Decode();
            
    //        if (scaleModifier == 0)
    //        {
    //            // Crop
    //            FluxImage imageOut = new ImageCropper(jpegIn.Image, cropArea).Crop();
    //            jpegOut = new DecodedJpeg(imageOut, jpegIn.MetaHeaders); // Retain EXIF details
    //        }
    //        else
    //        {
    //            // Resize
    //            jpegOut = new DecodedJpeg(new ImageResizer(jpegIn.Image).Resize(scaleModifier, ResamplingFilters.NearestNeighbor), jpegIn.MetaHeaders); // Retain EXIF details
    //        }

    //        // Encode
    //        MemoryStream outStream = new MemoryStream();
    //        new JpegEncoder(jpegOut, 90, outStream).Encode();

    //        // Display 
    //        outStream.Seek(0, SeekOrigin.Begin);
    //        return ConvertStreamToBuffer(outStream);

            //TODO: Rewire this
            return null;
        }
    }
}